#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "player.h"
#include "audioinput.h"

// 初始化静态变量
QAudioSource *MainWindow::m_audioSource = nullptr;
VideoInput *MainWindow::m_videoInput = nullptr;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    pstate = PSTATE_STOPED; // 通知播放器主线程退出
    player_stop();  // 结束录制
    player_exit();  // 释放播放器资源

    if (m_audioSource != nullptr)
        m_audioSource->stop();

    if (m_videoInput != nullptr)
        delete m_videoInput;
    delete ui;
}

int MainWindow::startVideoInput()
{
    m_videoInput = new VideoInput;

    return 0;
}

void MainWindow::on_videoRecordBtn_clicked()
{
    player_init(TYPE_VIDEO); // 让播放器模块开始自运行
    startVideoInput();  // 摄像头开始工作
    startAudioInput();  // 麦克风开始工作
    player_start();     // 开始录制
}

int MainWindow::startAudioInput()
{
    QAudioFormat AudioFormat;
    qDebug("Enter main()");

    AudioFormat.setSampleRate(44100);
    AudioFormat.setChannelCount(2);
    AudioFormat.setSampleFormat(QAudioFormat::Int16);

    AudioInput *audioInput = new AudioInput(AudioFormat);

    m_audioSource = new QAudioSource(QMediaDevices::defaultAudioInput(), AudioFormat);
    m_audioSource->start(audioInput);

    // m_audioSource->bufferSize() is 35287

    return 0;
}

void MainWindow::on_audioRecordBtn_clicked()
{
    player_init(TYPE_AUDIO); // 让播放器模块开始自运行
    startAudioInput();  // 麦克风开始工作
    player_start();     // 开始录制
}

